<!--
 * @Author: lemon 719771893@qq.com
 * @Date: 2025-03-01 13:00:34
 * @LastEditors: 李梦
 * @LastEditTime: 2025-03-08 00:25:48
 * @FilePath: /ranyu_anchor_new/src/views/register/components/BaseInfoForm.vue
 * @Description: 注册页面-BaseInfoForm组件
-->
<template>
  <div class="form-box">
    <el-form
      ref="ruleFormRef"
      :model="baseInfo"
      :rules="rules"
      label-width="auto"
      style="max-width: 600px"
      status-icon
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="baseInfo.name"
          placeholder="请输入您的真实姓名"
          :maxlength="10"
          clearable
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="baseInfo.age" placeholder="请输入您的年龄" maxlength="10" clearable />
      </el-form-item>

      <el-form-item label="证件类型" prop="idCardType">
        <el-select v-model="baseInfo.idCardType" placeholder="请选择" clearable>
          <el-option label="居民身份证" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="证件号" prop="papers">
        <el-input v-model="baseInfo.papers" placeholder="请输入" clearable maxlength="18" />
      </el-form-item>
      <el-form-item label="所在地区" prop="area">
        <el-cascader
          v-model="baseInfo.area"
          :options="areaList"
          :props="customProps"
          placeholder="请选择您的所在地区"
          clearable
          @change="handleChange"
        />
      </el-form-item>

      <el-form-item label="主播类型" prop="category">
        <el-select
          v-model="baseInfo.category"
          placeholder="请选择主播类型"
          clearable
          @change="handleSelectChange"
        >
          <template v-for="item in anchorType" :key="item.value">
            <el-option :label="item.label" :value="item.value" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="银行卡号" prop="bankNo">
        <el-input v-model="baseInfo.bankNo" placeholder="请输入" maxlength="20" clearable />
      </el-form-item>
      <el-form-item label="开户银行" prop="bank">
        <el-input v-model="baseInfo.bank" placeholder="请输入" maxlength="50" clearable />
      </el-form-item>
      <el-form-item label="银行卡扫描件">
        <FileUpload
          v-model="baseInfo.bankScanUrl"
          :data="{
            fileType: 4,
          }"
          :limit="1"
          :maxFileSize="100"
          accept=".jpeg,.png,.pdf"
        />
      </el-form-item>
      <el-form-item label="银行卡正面">
        <SingleImageUpload
          v-model="baseInfo.bankFrontUrl"
          :data="{
            fileType: 1,
          }"
          accept=".jpg,.png,.jpeg"
        />
      </el-form-item>
      <el-form-item label="银行卡反面">
        <SingleImageUpload
          v-model="baseInfo.bankReverseUrl"
          accept=".jpeg,.png,.pdf"
          :data="{
            fileType: 1,
          }"
        />
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button type="primary" @click="nextStep(ruleFormRef)">下一步</el-button>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "BaseInfoForm",
};
</script>

<script setup lang="ts">
import { ref, reactive, inject } from "vue";
import AuthAPI, { RegisterBaseInfo } from "@/api/auth/index";
import type { FormInstance, FormRules, CascaderValue } from "element-plus";
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";

// 传参回显
const props = defineProps({
  info: {
    type: Object,
    default: () => ({}),
  },
});
const emits = defineEmits(["nextStep"]);
const { getContract, fileName } = inject("contractUrl");

// 切换主播类型时触发
const handleSelectChange = (value: any) => {
  getContract(Number(value));
  fileName.value = anchorType.find((item) => item.value === Number(value))?.label;
};

const formatArea = (a: string, b: string, c: string): Array<string> => {
  if (a && !b && !c) return [a]; // 台湾省
  if (!a && b && c) return [b, c]; // 直辖市
  if (a && b && c) return [a, b, c]; // 省市区
  return [];
};

// 表单
const ruleFormRef = ref<FormInstance>();
const baseInfo = ref<RegisterBaseInfo>({
  ...props.info,
  bankScanUrl: props.info.bankScanUrl ? [props.info.bankScanUrl] : [],
  area: formatArea(props.info.province, props.info.city, props.info.district),
});
watch(
  () => props.info, // 监听 props.info
  (newVal) => {
    baseInfo.value = {
      ...newVal,
      area: formatArea(newVal.province, newVal.city, newVal.district),
      bankScanUrl: newVal.bankScanUrl ? [{ url: newVal.bankScanUrl }] : [],
    }; // 更新 baseInfo
    getContract(Number(newVal.idCardType)); // 获取合同模板
  },
  { immediate: true, deep: true } // 立即执行一次
);

// 年龄校验
const ageValidator = (rule: any, value: any, callback: any) => {
  if (value < 18) {
    callback(new Error("未成年人禁止注册"));
  } else {
    callback();
  }
};
// 校验规则
const rules = reactive<FormRules<RegisterBaseInfo>>({
  name: [{ required: true, message: "请输入", trigger: "blur" }],
  age: [
    { required: true, message: "请输入", trigger: "blur" },
    { pattern: /^\d+$/, message: "只能输入数字" },
    {
      validator: ageValidator,
      trigger: "blur",
    },
  ],
  idCardType: [{ required: true, message: "请选择", trigger: "change" }],
  papers: [
    { required: true, message: "请输入", trigger: "blur" },
    { pattern: /^\d+X?$/, message: "请输入正确的证件号：只能输入数字，且X只能出现在最后" },
  ],
  area: [{ required: true, message: "请选择", trigger: "change" }],
  category: [{ required: true, message: "请选择", trigger: "change" }],
  bankNo: [
    // { required: true, message: "请输入", trigger: "blur" },
    { pattern: /^\d+$/, message: "只能输入数字" },
  ],
  // bank: [{ required: true, message: "请输入", trigger: "blur" }],
});

let areaList = ref([]);
// 获取地区列表
const getArea = async () => {
  try {
    const res = await AuthAPI.getAreaList();
    areaList.value = res;
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  getArea();
});
const handleChange = (value: CascaderValue) => {
  baseInfo.value.province = "";
  baseInfo.value.city = "";
  baseInfo.value.district = "";
  if (value.length == 3) {
    baseInfo.value.province = value[0];
    baseInfo.value.city = value[1];
    baseInfo.value.district = value[2];
  } else if (value.length == 2) {
    // 直辖市
    baseInfo.value.province = "";
    baseInfo.value.city = value[0];
    baseInfo.value.district = value[1];
  } else {
    // 台湾省
    baseInfo.value.province = value[0];
  }
};

const customProps = {
  label: "name",
  children: "children",
  value: "name",
};

// 主播类型
const anchorType = [
  {
    label: "交友相亲",
    value: 1,
  },
  {
    label: "情感互动",
    value: 2,
  },
  {
    label: "悦耳声优",
    value: 3,
  },
  {
    label: "搞笑娱乐",
    value: 4,
  },
  {
    label: "游戏陪玩",
    value: 5,
  },
  {
    label: "哄睡剧场",
    value: 6,
  },
];

// 下一步
const nextStep = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("baseInfo.value:", baseInfo.value);
      emits("nextStep", {
        ...baseInfo.value,
        bankScanUrl:
          baseInfo.value.bankScanUrl.length !== 0 ? baseInfo.value.bankScanUrl[0].url : "",
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.form-box {
  width: 40%;
  height: auto;
  margin: 10px auto;
  text-align: center;
  padding: 20px;
  .remind {
    font-size: 12px;
    color: #ababab;
  }
  .btn {
    text-align: right;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
::v-deep .el-select {
  width: 400px !important;
}
::v-deep .el-input {
  width: 400px !important;
}
</style>
